package main.controller;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import static com.mongodb.client.model.Filters.eq;

import main.*;
import main.database.*;
import org.bson.Document;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
public class TopPageController {
    @RequestMapping(value = {"/toppage", "/toppage/{page}"})
    public String requestRankPage(@PathVariable(value="page") Optional<String> page, HttpServletRequest request, ModelMap modelMap) {
        String uuid = RequestHelper.getUserUUIDFromRequest(request);
        boolean isLogin = AccountHelper.isExistFromUUID(uuid);

        String type = "default";
        if (page.isPresent()) {
            type = page.get();
        }

        List<List<String>> parentList = processPage(uuid, type);

        long unread = 0;
        String user = "";
        if (isLogin) {
            user = uuid;
            unread = NotifyHelper.countUnreadNotify(uuid);
        }
        StatisticHelper.addTopPageAccess(uuid, NetworkHelper.getIPAddress(request), TimeHelper.getFormattedNowString(), UserAgentHelper.getUserAgent(request));

        String baseUrl = UriHelper.getServerBaseUri(request);
        List<String[]> top10CatlogList = CatlogHelper.getCatlogInfos(0);
        List<String[]> rankCatlogList = CatlogHelper.getCatlogInfos(1);
        modelMap.put("type", CatlogHelper.typeToString(type));
        modelMap.put("catlogList", top10CatlogList);
        modelMap.put("rankCatlogList", rankCatlogList);
        modelMap.put("contentList", parentList);
        modelMap.put("isLogin", isLogin);
        modelMap.put("serverUri", baseUrl);
        modelMap.put("unread", unread);
        modelMap.put("year2year", "2019 - " + TimeHelper.getFromattedCurrentYear());
        return "topPage";
    }

    private List<List<String>> processPage(String uuid, String type) {
        FindIterable<Document> documents = findSuitableDocuments(type);
        List<List<String>> parentList = new ArrayList<>();
        int index = 1;
        for (Document doc : documents) {
            List<String> childList = new ArrayList<>();

            String id = doc.get("_id").toString();
            String title = (String) doc.get("title");
            String catlog = (String) doc.get("catlog");
            String authorId = (String) doc.get("author");
            String author = AuthorHelper.getAuthorNameFromId(authorId);
            String score = ScoreHelper.getFormattedSecretScore((Double) doc.get("score"));

            childList.add(id);
            childList.add(title);
            childList.add(catlog);
            childList.add(author);
            childList.add(score);

            boolean collected = false;
            if (uuid == null || uuid.isEmpty()) {
                collected = false;
            }
            else {
                collected = CollectionHelper.checkUserCollection(uuid, id);
            }

            childList.add(collected ? "true": "false");

            childList.add(String.valueOf(index++));

            parentList.add(childList);
        }
        return parentList;
    }

    private FindIterable<Document> findSuitableDocuments(String type) {
        MongoCollection<Document> collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfArticle);

        FindIterable<Document> documents = null;
        Document sortMethod = new Document("score", -1);
        switch (type) {
            case "default":
            default:
                documents = collection.find().sort(sortMethod);
                break;
            case "zonghe":
                documents = collection.find().sort(sortMethod).limit(10);
                break;
            case "qihuan":
                documents = collection.find(eq("rootcatlog", "奇幻")).sort(sortMethod).limit(10);
                break;
            case "xuanhuan":
                documents = collection.find(eq("rootcatlog", "玄幻")).sort(sortMethod).limit(10);
                break;
            case "wuxia":
                documents = collection.find(eq("rootcatlog", "武侠")).sort(sortMethod).limit(10);
                break;
            case "xianxia":
                documents = collection.find(eq("rootcatlog", "仙侠")).sort(sortMethod).limit(10);
                break;
            case "dushi":
                documents = collection.find(eq("rootcatlog", "都市")).sort(sortMethod).limit(10);
                break;
            case "yanqing":
                documents = collection.find(eq("rootcatlog", "言情")).sort(sortMethod).limit(10);
                break;
            case "lishi":
                documents = collection.find(eq("rootcatlog", "历史")).sort(sortMethod).limit(10);
                break;
            case "junshi":
                documents = collection.find(eq("rootcatlog", "军事")).sort(sortMethod).limit(10);
                break;
            case "youxi":
                documents = collection.find(eq("rootcatlog", "游戏")).sort(sortMethod).limit(10);
                break;
            case "tiyu":
                documents = collection.find(eq("rootcatlog", "体育")).sort(sortMethod).limit(10);
                break;
            case "kehuan":
                documents = collection.find(eq("rootcatlog", "科幻")).sort(sortMethod).limit(10);
                break;
            case "lingyi":
                documents = collection.find(eq("rootcatlog", "灵异")).sort(sortMethod).limit(10);
                break;
        }

        return documents;
    }
}
